<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 100px;
      height: 100px;
    }
  </style>
</head>

<body>
  <div></div>
  <script>
    //1.自定义一个随机颜色函数
    function getRandomColor(flag = true) {
      //3.如果是true 则返回#ffffff
      if (flag) {
        let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']

        //法一：无脑法
        // return `#${arr[Math.floor(Math.random() * arr.length)]}${arr[Math.floor(Math.random() * arr.length)]}${arr[Math.floor(Math.random() * arr.length)]}${arr[Math.floor(Math.random() * arr.length)]}${arr[Math.floor(Math.random() * arr.length)]}${arr[Math.floor(Math.random() * arr.length)]}`

        //法二：字符串拼接
        let string = '#'
        for (let a = 1; a <= 6; a++) {
          let i = Math.floor(Math.random() * arr.length)
          string += arr[i]
        }
        return string

      } else {
        //4.否则是false 则返回rgb(255, 255, 255)
        let r = Math.floor(Math.random() * 256)
        let g = Math.floor(Math.random() * 256)
        let b = Math.floor(Math.random() * 256)
        return `rgb(${r}, ${g}, ${b})`
      }
    }

    //2.调用函数 getRandomColor(布尔值)
    console.log(getRandomColor(true))   //#ffffff
    console.log(getRandomColor())   //#ffffff
    console.log(getRandomColor(false))  //rgb(255, 255, 255)

    const div = document.querySelector('div')
    div.style.backgroundColor = getRandomColor()
    // div.style.backgroundColor = getRandomColor(true)
    console.log(div)

  </script>
</body>

</html>